package cn.coder.entity;

import cn.coder.exception.BusinessException;
import cn.coder.exception.ErrorCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Getter
@Setter
@ToString
@Accessors(chain = true)
public class Result<T> implements Serializable {

    private Result () {}

    private static final long serialVersionUID = 1L;

    private boolean success; // 操作是否成功
    private boolean failure; // 操作是否失败
    private T data; // 请求成功后返回的数据
    private String code; // 请求失败后返回的代码
    private String message; // 请求失败后返回的信息

    public static <T> Result<T> ok() {
        return new Result<T>().setSuccess(true).setFailure(false);
    }

    public static <T> Result<T> ok(T data) {
        return new Result<T>().setSuccess(true).setFailure(false).setData(data);
    }

    public static <T> Result<T> no() {
        return new Result<T>().setSuccess(false).setFailure(true);
    }

    public static <T> Result<T> no(String message) {
        return new Result<T>().setSuccess(false).setFailure(true).setMessage(message);
    }

    public static <T> Result<T> no(String code, String message) {
        return new Result<T>().setSuccess(false).setFailure(true).setCode(code).setMessage(message);
    }

    public static <T> Result<T> no(ErrorCode errorCode) {
        return new Result<T>().setSuccess(false).setFailure(true).setCode(errorCode.name()).setMessage(errorCode.message());
    }

    public static <T> Result<T> no(BusinessException exception) {
        return new Result<T>().setSuccess(false).setFailure(true).setCode(exception.getCode()).setMessage(exception.getMessage());
    }

}
